import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useRoleStore = defineStore('role', () => {
  const roles = ref([]);
  const loading = ref(false);

  const setRole = (list) => {
    roles.value = list;
  };

  const clearRole = () => {
    roles.value = [];
  };

  const getRole = async() => {
    if (roles.value && roles.value.length > 0) {
      return roles.value;
    }

    if (loading.value) {
      await sleep(100);
      return await getRole();
    }

    loading.value = true;
    const res = await api.post('/business/role/list').catch(() => {
      loading.value = false
    });
    if (res.code === '1') {
      loading.value = false;
      setRole(res.data);
      return roles.value;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return {
    getRole,
    clearRole
  };
});
